package com.expense.app.admin.handler;

import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.expense.common.exception.PlatformException;
import com.expense.common.util.Result;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.List;
import java.util.Set;

/**
 * 全局的的异常拦截器
 *
 * @author liuBin
 * @date 2018/09/09
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Log log = LogFactory.get();

    /**
     * 处理系统未知异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Result handleException(Exception e) {
        log.error("系统内部异常，异常信息：{}",e);
        e.printStackTrace();
        return Result.fail("系统内部异常");
    }


    /**
     * 处理内部警告异常
     * @param e
     * @return
     */
    @ExceptionHandler(PlatformException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Result handlePlatformException(PlatformException e) {
        log.error("系统警告：{}",e.getMessage());
        if(e.getCode() == null) return Result.fail(e.getMessage());
        return Result.fail(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_GATEWAY)
    @ResponseBody
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("参数错误：{}",e.getMessage());
        StrBuilder message = StrBuilder.create();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for(FieldError error:fieldErrors){
            message.append(error.getField()).append(":").append(error.getDefaultMessage()).append(",");
        };
        String msg = "";
        if(message.length()> 0) msg = message.subString(0,message.length()-1);
        return Result.fail(msg);
    }

    /**
     * 处理bind绑定对象传参验证
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_GATEWAY)
    @ResponseBody
    public Result handleBindException(BindException e) {
        log.error("参数错误：{}");
        StrBuilder message = StrBuilder.create();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for(FieldError error:fieldErrors){
            message.append(error.getField()).append(":").append(error.getDefaultMessage()).append(",");
        };
        String msg = "";
        if(message.length()> 0) msg = message.subString(0,message.length()-1);
        return Result.fail(msg);
    }

    /**
     * 处理普通参数传参验证异常
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_GATEWAY)
    @ResponseBody
    public Result handleConstraintViolationException(ConstraintViolationException e) {
        log.error("参数错误：{}");
        StrBuilder message = StrBuilder.create();
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        for(ConstraintViolation<?> violation: violations) {
            Path path = violation.getPropertyPath();
            String[] pathArr = StrUtil.split(path.toString(),".");
            message.append(pathArr[1]).append(violation.getMessage()).append(",");
        }
        String msg = "";
        if(message.length()> 0) msg = message.subString(0,message.length()-1);
        return Result.fail(msg);
    }
}
